<template>
  <div v-show="showBox" class="flex">
    <!-- 固定值 -->
    <a-input-number v-if="columnInfo.type === 'INTEGER'" v-model:value="formState.value" class="input-value" />
    <a-input v-else v-model:value="formState.value" class="input-value" />
  </div>
</template>
<script lang="ts">
  import { cloneDeep, isEqual } from 'lodash-es'
  import { computed, defineComponent, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'

  export default defineComponent({
    name: 'FixedAndDynamic',
    props: {
      columnInfo: {
        type: Object as PropType<FiledListType>,
        require: true,
        default: () => ({ type: 'VARCHAR' })
      },
      value: {
        type: Object,
        default: () => ({
          value: undefined,
          valueType: 'FIXED'
        })
      },
      conditionData: {
        type: Object as PropType<FormItemVisibleConditionData>,
        default: () => ({
          conditionType: '',
          value: ''
        })
      }
    },
    emits: ['update:value'],
    setup(props, { emit }) {
      const { t } = useI18n()
      const formState = ref({
        valueType: 'FIXED',
        value: undefined
      })

      const showBox = computed(() => {
        return props.conditionData?.conditionType
      })
      watch(
        () => cloneDeep(props.value),
        (newValue, oldValue) => {
          if (isEqual(newValue, oldValue)) {
            return
          }
          formState.value = props.value || {
            valueType: 'FIXED',
            value: undefined
          }
        },
        {
          deep: true,
          immediate: true
        }
      )
      watch(
        () => formState.value,
        () => {
          formState.value.valueType = 'FIXED'
          emit('update:value', formState.value)
        },
        {
          deep: true,
          immediate: true
        }
      )

      // 暴露给外部组件，用于验证
      function validate() {
        if (['', null, undefined].includes(formState.value.value)) {
          const tip = formState.value.valueType === 'FIXED' ? t('input') : t('select')
          return Promise.reject(tip)
        }
        return Promise.resolve(true)
      }
      return {
        t,
        formState,
        validate,
        showBox
      }
    }
  })
</script>
<style lang="less" scoped>
  .field-select {
    width: 200px;
  }

  .value-type {
    width: 90px;
    margin-right: 8px;
  }

  .input-value {
    width: 200px;
  }
</style>
<i18n>
zh-CN:
    input: 请输入
    select: 请选择
    fixed: 固定值
    dynamic: 动态值
en-US:
    input: please input
    select: please select
    fixed: fixed
    dynamic: dynamic
</i18n>
